package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.LowCodeHandlerFieldFactory;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.abstracts.AbstractLowCodeHandlerFieldService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.lowcodeexecute.pojo.LowCodeExecuteServicePojo;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/18 15:08
 */
@Service("lowCodeHandlerComboService")
public class LowCodeHandlerComboServiceImpl extends AbstractLowCodeHandlerFieldService {

    @Resource
    private ProFormHelp proFormHelp;

    @PostConstruct
    public void register() {
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.COMBO.getType(), this);
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.RADIO_GROUP.getType(), this);
    }

    @Override
    public Object handlerField(FieldAttrEntity fieldAttrEntity, JSONObject data, LowCodeExecuteServicePojo lowCodeExecuteServicePojo) throws XbbException {
        Object value = data.get(fieldAttrEntity.getAttr());
        if (Objects.isNull(value)) {
            return null;
        }
        List<ItemPoJo> itemList = proFormHelp.getItem(fieldAttrEntity, lowCodeExecuteServicePojo.getBusinessType(), lowCodeExecuteServicePojo.getCorpid(), lowCodeExecuteServicePojo.getFormId());
        fieldAttrEntity.setItems(itemList);
        ItemPoJo itemPoJo = new ItemPoJo();
        if (Objects.equals(fieldAttrEntity.getComboType(), ComboTypeEnum.CUSTOM.getType())) {
            String text = ItemUtil.getTextByValue(value, fieldAttrEntity);
            itemPoJo.setText(text);
            itemPoJo.setValue(value);
        } else {
            if (ItemUtil.isUUID(value.toString())) {
                String text = ItemUtil.getTextByValue(value, fieldAttrEntity);
                itemPoJo.setText(text);
                itemPoJo.setValue(value);
            } else {
                itemPoJo.setText(String.valueOf(value));
                itemPoJo.setValue(value);
            }
        }
        return itemPoJo;
    }
}
